package davel
//配置
import (
	"encoding/json"
	"os"
)

func NewDavelConfig(configFile string) *DavelConfig {
	//初始化配置
	davelConfig := &DavelConfig{
		ConfigData: make(map[string]string),
	}

	//AppPath, err := filepath.Abs(filepath.Dir(os.Args[0]))
	AppPath, err := os.Getwd()
	if  err != nil {
		panic( "项目目录获取失败：" + err.Error())
	}
	//设置项目目录
	davelConfig.AppPath = AppPath
	//设置系统默认配置路径
	davelConfig.ConfigPath = FileRealPath(davelConfig.AppPath + string(os.PathSeparator) + configFile)
	//加载配置文件
	davelConfig.LoadConfig(davelConfig.ConfigPath)
	return davelConfig
}

type DavelConfig struct {
	AppPath string //项目目录
	ConfigPath string //默认配置文件目录
	ConfigData map[string]string
}

//根据配置文件路径 重置配置
func (this *DavelConfig) ReloadConfig(filepath string) {
	//清空原有配置
	this.ConfigData = make(map[string]string)
	this.LoadConfig(filepath)
}

//根据配置文件路径加载配置
func (this *DavelConfig) LoadConfig(filename string)  {
	if FileExists(filename) {
		configContent := FileRead(filename)

		var jsonConfig map[string]string
		err := json.Unmarshal([]byte(configContent), &jsonConfig)
		if err==nil {
			this.ConfigData = jsonConfig
		}
	}
}

//获取int类型配置
func (this *DavelConfig) getDataInt64(key string,defaultValue int64) int64  {
	value,ok := this.ConfigData[key]
	if !ok {
		return defaultValue
	}
	return int64(StrToInt(value))
}

//获取int类型配置
func (this *DavelConfig) getDataInt(key string,defaultValue int) int  {
	value,ok := this.ConfigData[key]
	if !ok {
		return defaultValue
	}
	return StrToInt(value)
}

//获取string类型配置
func (this *DavelConfig) getDataString(key string,defaultValue string) string  {
	value,ok := this.ConfigData[key]
	if !ok {
		return defaultValue
	}
	return value
}

//获取int类型配置
func (this *DavelConfig) getDataBool(key string,defaultValue bool) bool  {
	value,ok := this.ConfigData[key]
	if !ok {
		return defaultValue
	}
	return value == "true"
}